<?php

session_save_path('sessions');
session_start();

// Connect to our database
include("include/dbconnection.php");

// Include our user class
include_once("include/user.php");

// Include our activity logger
include_once("include/activityLogger.php");


// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);

// Hash the password
$mypassword = sha1($mypassword);

// Create a null user object
$user = null;

// Create a logger object
$logger = new ActivityLogger($TABLE_LOGS, $TABLE_LOGS_LOGGEDAT, $TABLE_LOGS_USERID, $TABLE_LOGS_ACTIVITYTYPE, $TABLE_LOGS_EXTRACOMMENTS, $TABLE_LOGS_ID);

// Prepare the statement (in a very insecure way. Concordia is to blame, no support for MySQLi or PDO)
// The variables come from the dbtables.php file

$db_query = "SELECT
    u.$TABLE_USERS_USERID, u.$TABLE_USERS_USERTYPE, t.$TABLE_USERTYPE_USERDESCRIPTION,
    u.$TABLE_USERS_USERNAME, u.$TABLE_USERS_LASTCONNECTED, u.$TABLE_USERS_ENTRYDATE, u.$TABLE_USERS_EMAILADDRESS
    FROM $TABLE_USERS u
    LEFT JOIN $TABLE_USERTYPE t ON u.$TABLE_USERS_USERTYPE = t.$TABLE_USERTYPE_USERTYPE
    WHERE username='".$myusername."' AND password='".$mypassword."'";

$resultSet = mysql_query($db_query);
$result = mysql_fetch_array($resultSet);


// If AND ONLY IF we get 1 result, then we can log in
// Otherwise, set an error message and return to login page
if( mysql_numrows($resultSet) == 1 ) {

    // If the entry date != 0, then the user is active and can be logged in with
    if( $result[$TABLE_USERS_LASTCONNECTED] != 0 )
    {
        // Initialize our user object
        $user = new User();
        $user->setUserID($result[$TABLE_USERS_USERID]);
        $user->setUserType($result[$TABLE_USERS_USERTYPE]);
        $user->setUserDescription($result[$TABLE_USERTYPE_USERDESCRIPTION]);
        $user->setUsername($result[$TABLE_USERS_USERNAME]);
        $user->setLastConnected($result[$TABLE_USERS_LASTCONNECTED]);
        $user->setEntryDate($result[$TABLE_USERS_ENTRYDATE]);
        $user->setEmailAddress($result[$TABLE_USERS_EMAILADDRESS]);
        
        // If our user's type is a registered user, make sure that the blackmark amount is acceptable
        // Otherwise, log out and issue error message
        if( $user->getUserType() == $TABLE_USERTYPE_TYPEREGISTERED )
        {
            // Query for the blackmark value
            $blackmarkQuery = "SELECT $TABLE_REGISTEREDUSER_BLACKMARK 
                    FROM $TABLE_REGISTEREDUSER WHERE $TABLE_REGISTEREDUSER_USERID = ".$user->getUserID();
            $resultSet = mysql_query($blackmarkQuery);
            
            $result = mysql_fetch_array($resultSet);
            
            // If blackmarks are equal or more than 3...
            if($result[$TABLE_REGISTEREDUSER_BLACKMARK] >= 3 )
            {
                // Clear user
                $user = null;
                
                // Close the connection
                mysql_close();
                
                // Issue error message
                $_SESSION['loginError'] = "Your username has too many blackmarks and has been deactivated.";
                
                // Bounce back to login page
                header("location:main_login.php");
            }
            
            
        }

        // Convert our new user object into a string, so we can pass it between pages through session variables
        $serial_user = serialize($user);

        // Set the 'user' session variable to the string create above
        $_SESSION["user"] = $serial_user;

        // Log the activity
        $logger->addLogging($user->getUserID(), $TABLE_ACTIVITYTYPES_LOGGEDIN, $_SERVER['REMOTE_ADDR']);
        $logger->updateLastConnected($user->getUserID(), $TABLE_USERS, $TABLE_USERS_USERID, $TABLE_USERS_LASTCONNECTED);

        // Close the connection
        mysql_close();

        // Forward to successful login page
        header("location:login_success.php");
    }
    else // User isn't activated by administrator
    {
        // Close the connection
        mysql_close();
        $_SESSION['loginError'] = "Your username hasn't been activated by the administrator.";
        header("location:main_login.php");
    }

}
else {
    // Close the connection
    mysql_close();
    $_SESSION['loginError'] = "Incorrect username and/or password combination. Please try again.";
    header("location:main_login.php");
}